package models;

import java.util.List;

import play.db.ebean.Model;
import play.db.ebean.Model.Finder;

import javax.persistence.*;

import com.avaje.ebean.Page;
import com.avaje.ebean.validation.NotNull;

@Entity
public class Plot extends Model{

	@Id
	public Long id;
	
	@ManyToOne
	@NotNull
	public Subcompartment subcompartment;
	
	@OneToOne
	@NotNull
	public Shrub shrub;
	
	@OneToOne
	@NotNull
	public Topography topography;
	
	@OneToOne
	@NotNull
	public AnchorPoint anchorPoint;
	
	@OneToOne
	@NotNull
	public Investigation investigation;
	
	@NotNull
	public Float canopyDensity;
	
	//Finder
	public static Finder<Long, Plot> find = new Finder<Long, Plot>(
			Long.class, Plot.class);
	
	public static Plot getPlot(Plot plot) {
		return find.byId(plot.id);
	}
	
    /**
     * Return a page of Plot
     *
     * @param page Page to display
     * @param pageSize Number of computers per page
     * @param sortBy Computer property used for sorting
     * @param order Sort order (either or asc or desc)
     * @param filter Filter applied on the name column
     */
	
    public static Page<Plot> page(int page, int pageSize, String sortBy, String order, String filter) {
        return 
            find.where()
                .ilike("name", "%" + filter + "%")
                .orderBy(sortBy + " " + order)
                .fetch("subcompartment").fetch("shrub").fetch("topography").fetch("anchorPoint")
                .findPagingList(pageSize)
                .getPage(page);
    }
    
    /*算法*/
    /*单位面积蓄积量
     *平均年龄
     *树的个数
     *总蓄积量
     *优势树种
     *海拔 //暂不实现
     */
    
    /*未完成
     *
     */
    
    public double averageAge(){
    	List<Tree> tree = Tree.find.where().eq("plot", this).findList();
    	
    	int[] ages = new int[tree.size()];
    	double averageAge = 0;
    	
    	for( int i = 0; i < tree.size(); i++ ){
    		ages[i] = tree.get(i).age;
    	}
    	
    	for( int i = 0; i < tree.size(); i++ ){
    		averageAge += ages[i];
    	}
    	
    	return averageAge/tree.size();
    }
    
	public Integer numberOfTrees(){
		return Tree.find.where().eq("plot", this).findList().size();
	}
	
	public Float volumePerHa(){
		//单位面积蓄积量
		List<Tree> tree = Tree.find.where().eq("plot", this).findList();
		//where 
		Float volume = 0F;
		
		for( int i = 0; i < tree.size(); i++ ){
			volume += tree.get(i).volume();
		}
		
		Integer plotRadius = this.subcompartment.compartment.forest.plotRadius;
		
		return (float) (volume / (Math.pow(plotRadius, 2)*Math.PI));
	}
	
	public Float volume(){
		//总蓄积量
		List<Tree> tree = Tree.find.where().eq("plot", this).findList();
		//where 
		Float volume = 0F;
		
		for( int i = 0; i < tree.size(); i++ ){
			volume += tree.get(i).volume();
		}
		
		return (float) volume;
	}
	
//	public Species dominantSpecies(){
//		//优势树种（蓄积量最大）树种分类：specieskey
//		
//		//写入新list，排序，返回最大值的Species。
//	}
	
	public Float altitude(){
		//暂不实现
		return 0F;
	}
}
